﻿using Microsoft.EntityFrameworkCore;
using 订单处理系统.Entity;
using 订单处理系统.IService.impl;

namespace 订单处理系统.Hosted
{
    public class RedisInitializerHosted : BackgroundService
    {
        private readonly IRedisService _redisService;
        private readonly IServiceScopeFactory _scopeFactory;

        public RedisInitializerHosted(IRedisService redisService, IServiceScopeFactory scopeFactory)
        {
            _redisService = redisService;
            _scopeFactory = scopeFactory;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("开始初始化Redis缓存");
            using var scope = _scopeFactory.CreateScope();
            var _db = scope.ServiceProvider.GetRequiredService<OrderDbContext>();
            var product = await _db.Products.ToListAsync();
            foreach (var pro in product)
            {
                string redisKey = $"produc:{pro.Id}";
                await _redisService.SetIntAsync(redisKey, pro.Stock);
            }
            Console.WriteLine("初始化完成");
        }
    }
}